package com.jic.member.controller.manage;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.member.common.constant.RedisKeys;
import com.jic.member.entity.MemDiscountCardEntity;
import com.jic.member.exception.BussinessException;
import com.jic.member.request.*;
import com.jic.member.response.MemDiscountCardHistoryResponse;
import com.jic.member.response.MemDiscountCardResponse;
import com.jic.member.response.MemDiscountThemeResponse;
import com.jic.member.service.MemDiscountCardService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 折扣卡业务
 * @author MJ
 */
@Slf4j
@RestController
@RequestMapping("/memDiscountCard")
public class MemDiscountCardController {

    //线程池
    private static ExecutorService EXECUTORSERVICE = Executors.newFixedThreadPool(5);

    private static Integer ING_SECODES = 60 * 60;//60分钟

    @Resource
    MemDiscountCardService memDiscountCardService;

    @Autowired
    public RedisClientTemplate redisClientTemplate;


    @ApiOperation(value = "折扣卡生成")
    @ResponseBody
    @RequestMapping("/generateDiscountCard")
    public RestResult<String> generateDiscountCard(@RequestBody MemDiscountCardGenerateRequest request) {
        try{
            EXECUTORSERVICE.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        RestResult<String> restResult = memDiscountCardService.generateDiscountCard(request);
                    } catch (Exception e) {
                        log.error("generateDiscountCard error e = ", e);
                    }
                }
            });
            return RestResult.success("正在生成折扣卡，请稍候");
        }catch (Exception e){
            log.error("Meber generateDiscountCard error：",e);
            return RestResult.error("9999","系统异常，生成失败");
        }
    }

    @ApiOperation(value = "折扣卡列表")
    @ResponseBody
    @RequestMapping("/queryDiscountCardList")
    public RestResult<PageResult<MemDiscountCardResponse>> queryDiscountCardList(@RequestBody MemDiscountCardRequest request) {
        return RestResult.success(memDiscountCardService.queryDiscountCardList(request));
    }

    @ApiOperation(value = "绑定或者解绑折扣卡(单个)")
    @ResponseBody
    @RequestMapping("/bindingOrUntieDiscountCard")
    public RestResult bindingOrUntieDiscountCard(@RequestBody MemDiscountCardBindingRequest request) {
        String redisKey = RedisKeys.genDiscountCardThemeBindingUniteIngKey(request.getDiscountThemeId());
        try {
            Long setnx = redisClientTemplate.setnx(redisKey, "1");
            if(setnx == 0){
                return RestResult.error("9999", "当前有绑定/解绑任务正在进行，请稍后再试");
            }
            redisClientTemplate.expire(redisKey, ING_SECODES);
            return RestResult.success(memDiscountCardService.bindingOrUntieDiscountCard(request));
        } catch (BussinessException e) {
            log.error("bindingOrUntieDiscountCard e = {}, param = {}", e, JSON.toJSONString(request));
            return RestResult.error("9999", e.getMessage());
        } catch (Exception e) {
            log.error("bindingOrUntieDiscountCard e = {}, param = {}", e, JSON.toJSONString(request));
            return RestResult.error("9999", "系统异常");
        } finally {
            redisClientTemplate.del(redisKey);
        }
    }


    @ApiOperation(value = "绑定或者解绑折扣卡(批量)")
    @ResponseBody
    @RequestMapping("/batchBindingOrUntieDiscountCard")
    public RestResult batchBindingOrUntieDiscountCard(@RequestBody MemDiscountCardBatchBindingRequest request) {
        String redisKey = RedisKeys.genDiscountCardThemeBindingUniteIngKey(request.getDiscountThemeId());
        try {
            Long setnx = redisClientTemplate.setnx(redisKey, "1");
            if(setnx == 0){
                return RestResult.error("9999", "当前有绑定/解绑任务正在进行，请稍后再试");
            }
            redisClientTemplate.expire(redisKey, ING_SECODES);
            return RestResult.success(memDiscountCardService.batchBindingOrUntieDiscountCard(request));
        }catch (BussinessException e) {
            log.error("bindingOrUntieDiscountCard e = {}, param = {}", e, JSON.toJSONString(request));
            return RestResult.error("9999", e.getMessage());
        } catch (Exception e) {
            log.error("batchBindingOrUntieDiscountCard e = {}, param = {}", e, JSON.toJSONString(request));
            return RestResult.error("9999", "系统异常");
        } finally {
            redisClientTemplate.del(redisKey);
        }
    }

    @ApiOperation(value = "查询绑定总数和未绑定总数")
    @ResponseBody
    @RequestMapping("/queryBindingOrNoCount")
    public RestResult<MemDiscountCardResponse> queryBindingOrNoCount(@RequestBody MemDiscountCardBatchBindingRequest request) {
        return RestResult.success(memDiscountCardService.queryBindingOrNoCount(request));
    }

    @ApiOperation(value = "查询个人折扣卡绑定记录")
    @ResponseBody
    @RequestMapping("/discountCardHistory")
    public RestResult<List<MemDiscountCardHistoryResponse>> discountCardHistory(@RequestBody MemDiscountCardRequest request) {
        return RestResult.success(memDiscountCardService.discountCardHistory(request));
    }
}
